<template>
  <div class="edit-page-container">
    <!-- 面包屑导航 -->
    <!--    <Breadcrumb :items="breadcrumbItems" />-->

    <div class="content-container">
      <div class="page-title">
        <h3>{{ isEditMode ? '编辑数据' : '新增数据' }}</h3>
      </div>

      <!-- 表单卡片 -->
      <el-card class="form-card">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          class="edit-form"
        >
          <!-- 表单字段 -->
          <el-form-item label="公告标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入公告标题" />
          </el-form-item>
          <br />
          <el-form-item label="公告内容" prop="content">
            <el-input
              v-model="formData.content"
              type="textarea"
              :rows="4"
              placeholder="请输入公告内容"
            />
          </el-form-item>

          <!--          <el-form-item label="描述" prop="description">-->
          <!--            <el-input-->
          <!--                v-model="formData.description"-->
          <!--                placeholder="请输入描述"-->
          <!--                type="textarea"-->
          <!--                :rows="3"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="分类" prop="category">-->
          <!--            <el-select v-model="formData.category" placeholder="请选择分类">-->
          <!--              <el-option label="分类A" value="category_a" />-->
          <!--              <el-option label="分类B" value="category_b" />-->
          <!--              <el-option label="分类C" value="category_c" />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->

          <!--          <el-form-item label="日期" prop="date">-->
          <!--            <el-date-picker-->
          <!--                v-model="formData.date"-->
          <!--                type="date"-->
          <!--                placeholder="选择日期"-->
          <!--            />-->
          <!--          </el-form-item>-->

          <!--          <el-form-item label="附件" prop="attachment">-->
          <!--            <el-upload-->
          <!--                action="#"-->
          <!--                :show-file-list="false"-->
          <!--                :on-success="handleUploadSuccess"-->
          <!--                class="upload-btn"-->
          <!--            >-->
          <!--              <el-button type="primary" size="small">上传文件</el-button>-->
          <!--            </el-upload>-->
          <!--            <span v-if="formData.attachment" class="uploaded-file">-->
          <!--              {{ formData.attachment.name }}-->
          <!--              <el-button-->
          <!--                  type="text"-->
          <!--                  size="mini"-->
          <!--                  @click="removeAttachment"-->
          <!--                  class="ml-2"-->
          <!--              >-->
          <!--                移除-->
          <!--              </el-button>-->
          <!--            </span>-->
          <!--          </el-form-item>-->

          <!-- 表单操作按钮 -->
        </el-form>
        <el-form-item class="form-actions">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveData">保存</el-button>
        </el-form-item>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Breadcrumb from '@/components/breadcrumb/index.vue'
import api from '@/api/news'
import { ElMessage } from 'element-plus'
import { TeacherInfo } from '@/stores/counter'
// import { title } from 'process'

const router = useRouter()
const route = useRoute()
const teacherData=TeacherInfo()

// 表单引用
const formRef = ref(null)

// 表单数据
const formData = ref({
  id:'',
  content:'',
  title:'',
  createName:'',
  amendName:'',
})
let loading = ref(false)
// 表单验证规则
const rules = reactive({})

// 面包屑数据
const breadcrumbItems = [
  { label: '首页', path: '/' },
  { label: '数据管理', path: '/data' },
  // { label: isEditMode ? '编辑数据' : '新增数据' }
]

// 判断是否为编辑模式
const isEditMode = ref('')

// 模拟获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      id: route.params.id,
    }
    formData.value.id=params.id
    const response = await api.selectAll(params)
    if (response.code == 200) {
      // 根据你的API设计调整
      formData.value = response.data
      console.log(' formData.value+', formData.value, response.data.list)
    } else {
      // API返回了错误码
      throw new Error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    // 友好的错误提示
    ElMessage.error({
      message: error.message || '加载数据失败，请稍后重试',
      duration: 3000,
    })
    // 重置数据防止显示旧数据
    formData.value = []
  } finally {
    loading.value = false
  }
}
const saveData = async () => {
  let response
  // 表单验证
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 模拟API请求
      // const apiMethod = isEditMode.value ? 'PUT' : 'POST';

      if (isEditMode.value) {
        formData.value.amendName=teacherData.getTeacherName
        console.log("修改人数据："+formData.value.amendName)
        response = await api.update(formData.value)
      } else {
        formData.value.createName=teacherData.getTeacherName
        response = await api.insert(formData.value)
      }
      // 显示成功消息
      ElMessage.success(isEditMode.value ? '数据更新成功' : '数据创建成功')
      // 返回列表页
      router.push('/NewsPage')
    }
  })
}

// 取消编辑
const cancelEdit = () => {
  router.push('/NewsPage')
}
// 移除附件
// 初始化数据
onMounted(() => {
  console.log(route.params, 'route.params')
  if (route.params.id != null || route.params.id != undefined) {
    isEditMode.value = true
    const id = route.params.id
    fetchData(id)
  } else {
    isEditMode.value = false
  }
})

// // 监听路由变化，更新面包屑
// watch(
//     () => route.params.id,
//     (newId) => {
//       console.log("newId",newId)
//       isEditMode.value = !!newId;
//       breadcrumbItems[2].label = isEditMode.value ? '编辑数据' : '新增数据';
//
//       if (isEditMode.value) {
//         fetchData(newId);
//       } else {
//         // 重置表单
//         Object.assign(formData, {
//           id: null,
//           name: '',
//           description: '',
//           status: 'active',
//           category: 'category_a',
//           date: null,
//           attachment: null,
//         });
//       }
//     }
// );
</script>

<style scoped>
.edit-page-container {
  padding: 20px;
}

.content-container {
  margin-top: 20px;
}

.page-title {
  margin-bottom: 20px;
}

.form-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
.el-form-item {
  align-items: center;
}
.edit-form {
  margin-top: 20px;
  display: grid;
  grid-template-columns: 50% 50%;
}

.form-actions {
  margin-top: 30px;
  text-align: right;
}
.upload-btn {
  display: inline-block;
  vertical-align: middle;
}
:deep(.el-form-item__content) {
  justify-content: center !important;
}
.uploaded-file {
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
}
</style>
